#!/usr/bin/env bash
set -euo pipefail

# Usage: ./generate-nginx-config.sh <groupId> <server_name> [/base_path] [api_host] [out_file]
# Default base_path=/ide, api_host=http://localhost:8080, out_file=./nginx-shared-${groupId}.conf

GROUP_ID=${1:-}
SERVER_NAME=${2:-}
BASE_PATH=${3:-/ide}
API_HOST=${4:-http://localhost:8080}
OUT_FILE=${5:-}

if [[ -z "$GROUP_ID" || -z "$SERVER_NAME" ]]; then
  echo "Usage: $0 <groupId> <server_name> [/base_path] [api_host] [out_file]" >&2
  exit 1
fi

if [[ -z "$OUT_FILE" ]]; then
  OUT_FILE="./nginx-shared-${GROUP_ID}.conf"
fi

# normalize base path
if [[ "${BASE_PATH}" != /* ]]; then BASE_PATH="/${BASE_PATH}"; fi
BASE_PATH="${BASE_PATH%/}"

echo "Generating nginx config to ${OUT_FILE} ..."
curl -fsSL "${API_HOST}/api/users/shared/environment/ide/nginx?groupId=${GROUP_ID}&serverName=${SERVER_NAME}&basePath=${BASE_PATH}&operatorRole=admin" \
  -o "${OUT_FILE}"

echo "Done. File: ${OUT_FILE}"

